import { CONSOLE_REQUEST_ENABLE, CONSOLE_RESPONSE_ENABLE } from '@/config'
import Vue from 'vue'
import { clearLoginInfo } from '@/utils'
import router from '@/router'

export function requestSuccessFunc (requestObj) {
  // 自定义请求拦截逻辑，可以处理权限，请求发送监控等
  // ...
  requestObj.headers['token'] = Vue.cookie.get('token')
  if (CONSOLE_REQUEST_ENABLE) {
    console.info('requestSuccessFunc', `url: ${requestObj.url}`, requestObj)
  }
  return requestObj
}

export function requestFailFunc (requestError) {
  // 自定义发送请求失败逻辑，断网，请求发送监控等
  // ...
  if (CONSOLE_RESPONSE_ENABLE) {
    console.info('requestError', requestError)
  }
  return Promise.reject(requestError)
}

export function responseSuccessFunc (responseObj) {
  const { code } = responseObj.data

  if (code === 401) {
    clearLoginInfo()
    router.push({ name: 'login' })
  }
  if (CONSOLE_RESPONSE_ENABLE) {
    console.info('responseSuccessFunc', `url: ${responseObj.url}, code: ${code}`, responseObj)
  }
  return responseObj
}

export function responseFailFunc (responseError) {
  // 响应失败，可根据 responseError.message 和 responseError.response.status 来做监控处理
  // ...
  const code = window.R.pathOr(-1, ['response', 'status'], responseError)

  if (CONSOLE_RESPONSE_ENABLE) {
    console.info('responseError', responseError, `code: ${code}`)
  }
  return Promise.reject(responseError)
}
